//
//  String+Emoticon.swift
//  04.微博文本转表情
//
//  Created by yaochunlin on 16/5/3.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

extension String {

    //将微博内容中表情字符串替换为表情图片
    func emoticonNameTextToPicAttText() -> NSAttributedString {
        
        //将普通文本转化为属性文本方便后续操作
        let attrText = NSMutableAttributedString.init(string: self)
        
        //        1.找到微博文本中的表情名称 []
        //利用正则表达式
        let pattern = "\\[.*?\\]"
        
        let regular = try! NSRegularExpression.init(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        //匹配
        let results = regular.matchesInString(self, options: [], range: NSRange.init(location: 0, length: self.characters.count))
        
        //反过来遍历(这样不会影响前面的范围)
        for result in results.reverse() {
            
            let range = result.rangeAtIndex(0)
            
            //截取匹配的名称
            let emoticonName = (self as NSString).substringWithRange(range)
            print("匹配的结果: \(emoticonName )")
            
            //2.用表情名称去找模型
            
            if let emoticonModel = YCLEmoticonModel.emoticonNameToEmoticonModel(emoticonName) {
                
                //3.将图片转化为带附件的属性文本
                let attrM = emoticonModel.emoticonModelToAttrText(UIFont.systemFontOfSize(15))
                
                //4.将表情名称替换为属性文本
                attrText.replaceCharactersInRange(range, withAttributedString: attrM)
            }
        }
        
        return attrText
        
        
    }

}